<template>
  <div class="user-management">
    <!-- 搜索和操作区域 -->
    <div class="operation-container">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="姓名">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-select
            v-model="queryParams.sex"
            placeholder="请选择性别"
            clearable
            style="width: 100px"
          >
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            v-permission="'user:query'"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="button-group">
        <el-button type="primary" v-permission="'user:add'" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增用户
        </el-button>
      </div>
    </div>

    <!-- 用户表格 -->
    <el-table
      :data="userList"
      border
      stripe
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="phone" label="电话" width="120" />
      <el-table-column prop="sex" label="性别" width="120" />
      <el-table-column label="身份" width="120">
        <template #default="{ row }">
          <span v-if="row.roleCode === 1">超级管理员</span>
          <span v-else-if="row.roleCode === 2">医疗管理员</span>
          <span v-else-if="row.roleCode === 3">财务管理员</span>
          <span v-else-if="row.roleCode === 4">数据分析师</span>
          <span v-else-if="row.roleCode === 5">经理</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-switch
            v-permission="'user:status'"
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button
            v-permission="'user:edit'"
            size="small"
            @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button
            v-permission="'user:delete'"
            size="small"
            type="danger"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
      <el-form
        ref="userForm"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="formData.sex" placeholder="选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="身份" prop="roleCode">
          <el-select v-model="formData.roleCode" placeholder="请选择身份">
            <el-option label="超级管理员" value="1" />
            <el-option label="医疗管理员" value="2" />
            <el-option label="财务管理员" value="3" />
            <el-option label="数据分析员" value="4" />
            <el-option label="经理" value="5" />
          </el-select>
        </el-form-item>
        <div v-if="isAdd" class="default-password-info">
          默认密码为:123456(系统自动分配,无需手动输入)
        </div>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getUserList,
  addUser,
  updateUser,
  deleteUser,
  changeUserStatus
} from '@/api/user'

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  name: '',
  sex: ''
})

// 表格数据
const userList = ref([])
const total = ref(0)
const loading = ref(false)

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAdd = ref(true)

// 表单数据
const formData = reactive({
  id: null,
  username: '',
  name: '',
  password: '',
  phone: '',
  sex: '',
  roleCode: '',
  status: 1
})

// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  roleCode: [{ required: true, message: '请选择身份', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号格式',
      trigger: 'blur'
    }
  ]
})

// 获取用户列表
const fetchUserList = async () => {
  try {
    loading.value = true
    const res = await getUserList(queryParams)
    userList.value = res.data.data.records
    total.value = res.data.data.total
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.page = 1
  fetchUserList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.username = ''
  queryParams.name = ''
  queryParams.sex = ''
  handleQuery()
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchUserList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  queryParams.page = val
  fetchUserList()
}

// 状态切换
const handleStatusChange = async (row) => {
  try {
    await changeUserStatus(row.id, row.status)
    ElMessage.success('状态更新成功')
  } catch (error) {
    // 如果请求失败，恢复原来的状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 新增用户
const handleAdd = () => {
  dialogTitle.value = '新增用户'
  isAdd.value = true
  resetForm()
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  isAdd.value = false
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该用户吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true // 添加居中属性
  })
    .then(async () => {
      await deleteUser(row.id)
      ElMessage.success('删除成功')
      fetchUserList()
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    username: '',
    name: '',
    password: '',
    status: 1
  })
}

// 提交表单
const submitForm = async () => {
  try {
    if (isAdd.value) {
      await addUser(formData)
      ElMessage.success('新增成功')
    } else {
      await updateUser(formData)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    fetchUserList()
  } catch (error) {
    console.error(error)
  }
}

// 初始化加载数据
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
:global(.el-message-box) {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.el-message-box__content {
  text-align: center;
}
.user-management {
  padding: 20px;
}

.operation-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.button-group {
  margin-left: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
.default-password-info {
  font-size: 14px;
  color: #999;
  margin-bottom: 15px;
}
.el-select {
  width: 100%;
}
</style>
